package com.zx.idc.backend.gui.sys;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zx.idc.backend.gui.common.BaseApi;
import com.zx.idc.backend.gui.common.Result;
import com.zx.idc.backend.gui.common.base.BaseAddApi;
import com.zx.idc.backend.gui.common.base.BaseUpdateApi;
import com.zx.idc.common.ref.copy.BeanCopyUtil;
import com.zx.idc.ds.sys.entity.SysRole;
import com.zx.idc.ds.sys.entity.SysUserRole;
import com.zx.idc.ds.sys.service.ISysRoleService;
import com.zx.idc.ds.sys.service.ISysUserRoleService;
import com.zx.idc.ds.sys.vo.SysRoleVo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色（用户组） 前端控制器
 * </p>
 *
 * @author rxliuli
 * @since 2019-01-31
 */
@RestController
@RequestMapping("/api/sysRole")
public class SysRoleController extends BaseApi implements BaseAddApi<ISysRoleService, SysRole>, BaseUpdateApi<ISysRoleService, SysRole> {
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";

    @Autowired
    private ISysRoleService service;
    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Override
    public Optional<ISysRoleService> getService() {
        return Optional.of(service);
    }

    @GetMapping("/list-for-all")
    @RequiresPermissions(value = {"transaction-log:transaction-log"
        , "transaction-log:t-log-active"
        , "transaction-log:t-log-security"
        , "transaction-log:t-log-operation"
    }, logical = Logical.OR)
    public Result<List<SysRole>> listForAll() {
        return success(
            service.listForAll().stream()
                .map(sr ->
                    BeanCopyUtil.copy(sr, new SysRoleVo())
                        .exec()
                        .get()
                        .setUserCount(sysUserRoleService.selectCount(new SysUserRole().setRoleId(sr.getId())))
                )
                .collect(Collectors.toList())
        );
    }

    @GetMapping("/select-list")
    public Result<List<SysRole>> selectList() {
        return success(
            service.selectList(
                new EntityWrapper<SysRole>().setSqlSelect(COLUMN_ID, COLUMN_NAME)
            )
        );
    }

    @PostMapping("/delete/{id}")
    @RequiresPermissions("system-configuration:sys-user:edit")
    public Result<Boolean> delete(@PathVariable Integer id) {
        final int count = sysUserRoleService.selectCount(new SysUserRole().setRoleId(id));
        if (count > 0) {
            return error(String.format("当前管理员组下还存在 %d 位管理员，不能直接删除！", count));
        }
        return success(service.deleteById(id));
    }

    @GetMapping("/get/{id}")
    public Result<SysRoleVo> get(@PathVariable Integer id) {
        return success(service.get(id));
    }

    @PostMapping("/update-user-role")
    @RequiresPermissions("system-configuration:sys-user:edit")
    public Result<Boolean> updateUserRole(@RequestBody SysRoleVo sysRoleVo) {
        return success(service.updateUserRole(sysRoleVo));
    }

    @PostMapping("/update-sys-menu")
    @RequiresPermissions("system-configuration:sys-user:edit")
    public Result<Boolean> updateSysMenu(@RequestBody SysRoleVo sysRoleVo) {
        return success(service.updateSysMenu(sysRoleVo));
    }

    @GetMapping("/get/user-id/{userId}")
    public Result<List<SysRole>> getByUserId(@PathVariable("userId") Integer userId) {
        return success(
            service.getRolesByUserId(userId)
        );
    }

    @Override
    @RequiresPermissions("system-configuration:sys-user:edit")
    public Result<Boolean> add(@RequestBody SysRole entity) {
        return build(service.insert(entity.setCreateTime(LocalDateTime.now()).setStatus(1)));
    }
}

